package cz.muni.fi.pv168.confusinglibrary;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Riema
 */
public class AuthorManagerImpl implements AuthorManager{
    private List<Author> testingList = new ArrayList<Author>();
    private static long idCount = 1;

    public Author addAuthor(Author author){
        if (author == null){
            throw new NullPointerException("author");
        }
        if (author.getId() != null){
            throw new IllegalArgumentException("Author is already in list.");
        }

        author.setId(idCount);
        AuthorManagerImpl.changeIdCount();
        this.testingList.add(author);
        return author;
    }

    private static void changeIdCount(){
        AuthorManagerImpl.idCount++;
    }

    public void removeAuthor(Author author){
        if (author == null){
            throw new NullPointerException("author");
        }
        if (!this.testingList.remove(author)){
            throw new IllegalArgumentException("Author doesn't exist.");
        }

        author.setId(null);
    }

    public void updateAuthor(Author author){
        if (author == null){
            throw new NullPointerException("author");
        }

        if (!this.testingList.remove(author)){
            throw new IllegalArgumentException("Author doesn't exist.");
        }

        testingList.add(author);
    }

    public List<Author> getAllAuthors(){
        return this.testingList;
    }

    public Author findAuthorById(Long id){
        for (Author aut : this.testingList){
            if (aut.getId().equals(id)){
                return aut;
            }
        }
        return null;
    }

    public List<Author> findAuthorsByName(String name){
        return findAuthorsByName(name, null);
    }

    public List<Author> findAuthorsByName(String surname, String name){
        if (surname == null){
            throw new NullPointerException("surname");
        }

        List<Author> authors = new ArrayList<Author>();

        for (Author author : this.testingList){
            if (author.getSurname().equals(surname)){
                if (name == null){
                    authors.add(author);
                }
                else{
                    if (author.getName().equals(name)){
                        authors.add(author);
                    }
                }
            }
        }
        return authors;
    }
}
